﻿using Bricks.Business.Models.Account;
using Bricks.Component.Utils;
using Bricks.Business.Data.Repositories.Account;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Bricks.Business.Data.Repositories.BidManagement;
using Bricks.Business.Models.BidManagement;
using Bricks.Business.Data.Repositories.ProjectContract;
using Bricks.Site.Models.BidInfo;
using Bricks.Business.Data.Repositories.Document;

namespace Bricks.Business.Service.Impl
{
    /// <summary>
    /// 招标管理
    /// </summary>
    [Export(typeof(IBidInfoService))]
    public class BidInfoService : IBidInfoService
    {
        [Import]
        protected IBidInfoRepository BidInfoRepository { get; set; }

        [Import]
        protected IProjectInfoRepository ProjectInfoRepository { get; set; }

        [Import]
        protected ISectionInfoRepository SectionInfoRepository { get; set; }

        [Import]
        protected IDocumentInfoRepository DocumentInfoRepository { get; set; }

        public IQueryable<BidInfo> Bids
        {
            get { return BidInfoRepository.Entities; }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<BidListView> GetDataList()
        {
            List<BidListView> result = new List<BidListView>();
            var bidList = (from bid in BidInfoRepository.Entities
                           join project in ProjectInfoRepository.Entities on bid.ProjectID equals project.ID
                           select new BidListView
                           {
                               ID = bid.ID,
                               ProjectName = project.ProjectName,
                               BidDate = bid.BidDate,
                               BidCount = 0,
                               BidTitle = bid.BidTitle,
                               BidType = bid.BidType
                           }).ToList();

            //招标数量（根据招标ID从标段数据中取）
            foreach (var bid in bidList)
            {
                bid.BidCount = this.GetBidCount(bid.ID);
            }
            result = bidList.OrderBy(m => m.ProjectName).ThenBy(m => m.BidDate).ToList();
            return result;
        }

        /// <summary>
        /// 获取招标列表（根据项目ID）
        /// </summary>
        /// <param name="projectID"></param>
        /// <returns></returns>
        public List<BidInfo> GetBidsByProjectID(Guid projectID)
        {
            List<BidInfo> result = new List<BidInfo>();
            var bidList = from bid in BidInfoRepository.Entities
                          join project in ProjectInfoRepository.Entities on bid.ProjectID equals project.ID
                          where bid.ProjectID == projectID
                          select bid;
            result = bidList.OrderBy(m => m.BidDate).ToList();
            return result;
        }

        /// <summary>
        /// 获取招标数量（根据招标ID从标段数据中取）
        /// </summary>
        /// <param name="bidID"></param>
        /// <returns></returns>
        private int GetBidCount(Guid bidID)
        {
            int result = 0;
            result = SectionInfoRepository.Entities.Count(m => m.BidID == bidID);
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Add(BidInfo model)
        {
            BidInfo record = model.CopyTo<BidInfo>();
            //record.ID = GuidHelper.NewGuid();
            BidInfoRepository.Insert(record);
            return new OperationResult(OperationResultType.Success, "新增成功", record);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Modify(BidInfo model)
        {
            PublicHelper.CheckArgument(model, "model");
            BidInfo record = Bids.FirstOrDefault(m => m.ID == model.ID);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            record = model.CopyTo<BidInfo>();
            if (BidInfoRepository.Update(record) >= 0)
                return new OperationResult(OperationResultType.Success, "修改成功", record);
            return new OperationResult(OperationResultType.Error, "保存失败");
        }

        /// <summary>
        /// 删除（需关联删除标段）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(Guid id)
        {
            BidInfo record = Bids.FirstOrDefault(m => m.ID == id);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            //找出关联的标段记录
            var sectionList = SectionInfoRepository.Entities.Where(m => m.BidID == id);
            if (sectionList != null && sectionList.Count() > 0)
            {
                var sectionIDs = from m in sectionList
                                 select m.ID;
                if(sectionIDs!=null && sectionIDs.Count()>0)
                {
                    var documentList = DocumentInfoRepository.Entities.Where(m => sectionIDs.Contains(m.InstanceID));
                    if(documentList!=null && documentList.Count()>0)
                    {
                        DocumentInfoRepository.Delete(documentList);
                    }
                }
                //删除关联标段记录
                SectionInfoRepository.Delete(sectionList);
            }

            if (BidInfoRepository.Delete(record) >= 0)
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            return new OperationResult(OperationResultType.Error, "删除失败");
        }

        /// <summary>
        /// 获取标段列表（根据招标ID）
        /// </summary>
        /// <param name="bidID"></param>
        /// <returns></returns>
        public List<SectionListView> GetSectionList(Guid bidID)
        {
            List<SectionListView> result = new List<SectionListView>();
            //var sectionList = SectionInfoRepository.Entities.Where(m => m.BidID == bidID);
            //result = sectionList.OrderBy(m => m.AddDate).ToList();

            var sectionList = from m in SectionInfoRepository.Entities
                              where m.BidID == bidID
                              orderby m.AddDate
                              select new SectionListView
                              {
                                  IsChecked = false,
                                  ID = m.ID,
                                  SectionName = m.SectionName,
                                  BidFile = m.BidFile,
                                  BidUnit = m.BidUnit,
                                  BidMoney = m.BidMoney,
                                  EnterBidFile = m.EnterBidFile
                              };
            result = sectionList.OrderBy(m => m.SectionName).ToList();
            return result;
        }

        /// <summary>
        /// 保存标段列表
        /// </summary>
        /// <param name="bidID"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public OperationResult SaveSectionList(Guid bidID, List<SectionListView> list)
        {
            //清空已有的数据
            var existSectionList = SectionInfoRepository.Entities.Where(m => m.BidID == bidID);
            if (existSectionList != null && existSectionList.Count() > 0)
            {
                SectionInfoRepository.Delete(existSectionList);
            }

            //重新补充现有列表数据
            foreach (SectionListView view in list)
            {
                //var record = SectionInfoRepository.Entities.FirstOrDefault(m => m.ID == view.ID);
                ////编辑
                //if (record != null)
                //{
                //    record = view.CopyTo<SectionInfo>();
                //    record.BidID = bidID;
                //    SectionInfoRepository.Update(record);
                //}
                ////新增
                //else
                //{
                SectionInfo newSection = view.CopyTo<SectionInfo>();
                //newSection.ID = GuidHelper.NewGuid();
                newSection.BidID = bidID;
                SectionInfoRepository.Insert(newSection);
                //}
            }
            return new OperationResult(OperationResultType.Success, "保存成功");
        }

        /// <summary>
        /// 根据标段ID获取标段名称（格式：项目1-招标1-标段1，项目1-招标2-标段3）
        /// </summary>
        /// <param name="secitonIDs"></param>
        /// <returns></returns>
        public string GetFullSectionNameByID(List<Guid> secitonIDs)
        {
            string result = string.Empty;
            if (secitonIDs != null && secitonIDs.Count > 0)
            {
                var list = from section in SectionInfoRepository.Entities
                           join bid in BidInfoRepository.Entities on section.BidID equals bid.ID
                           join project in ProjectInfoRepository.Entities on bid.ProjectID equals project.ID
                           where secitonIDs.Contains(section.ID)
                           select new
                           {
                               ProjectName = project.ProjectName,
                               BidTitle = bid.BidTitle,
                               SectionName = section.SectionName
                           };
                if (list != null && list.Count() > 0)
                {
                    List<string> fullSectionNames = new List<string>();
                    foreach (var item in list)
                    {
                        fullSectionNames.Add(string.Format("{0}-{1}-{2}", item.ProjectName, item.BidTitle, item.SectionName));
                    }
                    result = string.Join(",", fullSectionNames);
                }
            }
            return result;
        }
    }
}
